package vn.edu.uit.chemistry.utilities;

import java.io.IOException;
import java.net.ServerSocket;

import android.content.Context;

public class TCPServerCommand implements Runnable{

	private ServerSocket serverSocket;
	private Thread thread;
	
	Context ctx;
	public TCPServerCommand(Context _ctx) {
		this.ctx = _ctx;
	}
	
//	public static TCPServer getInstance() {
//		if (server == null) {
//			server = new TCPServer();
//		}
//		
//		return server;
//	}
	
	public boolean start() {
		try {
			serverSocket = new ServerSocket(54321);
			System.out.println("Wating for clients...");
			thread = new Thread(this);
			thread.start();
			while(!thread.isAlive()) {
				//
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public boolean stop() {
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public void run() {
		while(true) {
			try {
				new ClientThreadCommand(serverSocket.accept(), ctx).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
